package address

import (
	"context"
	"encoding/json"

	"laundry-service/app/client/internal/svc"
	"laundry-service/app/client/internal/types"
	"laundry-service/entity"

	"github.com/zeromicro/go-zero/core/logx"
)

type SetDefaultAddressLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSetDefaultAddressLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SetDefaultAddressLogic {
	return &SetDefaultAddressLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SetDefaultAddressLogic) SetDefaultAddress(req *types.SetDefaultAddressReq) (resp *types.Reply, err error) {
	userId, _ := l.ctx.Value("userId").(json.Number).Int64()

	if err := l.svcCtx.Db.ClearAddrPreDefault(userId); err != nil {
		return nil, err
	}

	var newDefaultAddress entity.Address
	newDefaultAddress.ID = req.Id
	if err := l.svcCtx.Db.SetDefaultAddr(&newDefaultAddress); err != nil {
		return nil, err
	}

	return nil, nil
}
